<template>
    <div>
        <div style="box-shadow:#ccc 0px 0px 10px;width: 100%;height:100%;background-color: white">
            <div style="width: 98%;height: 630px;margin-left: 10px">
                <el-tabs v-model="activeName">
                    <el-tab-pane label="个人信息" name="first">
                        <el-row>
                            <el-col :span="6">
                                <div style="margin-left: 60px;margin-top:70px;width:150px;height:150px">
                                    <img :src="empform.empImgpath"  style="width:150px;height:150px"/>
                                </div>
                                <div class="footerBtn" style="margin-left: -60px">
                                    <el-button @click="clickUpload">上传头像</el-button>

                                </div>
                            </el-col>
                            <el-col :span="14">
                                <el-form :model="empform" :label-position="labelPosition" >
                                    <div style="margin-top: -38px;height: 400px">
                                        <div style="height: 150px;margin-left: 10px;">
                                            <el-row type="flex" style="margin-top: 120px">
                                                <el-col :span="3">
                                                    <span style="color: gray">姓名：</span>
                                                </el-col>
                                                <el-col :span="9">
                                                    <span style="color: black">{{empform.empName}}</span>
                                                </el-col>
                                                <el-col :span="3">
                                                    <span style="color: gray">性别：</span>
                                                </el-col>
                                                <el-col :span="4">
                                                    <span style="color: black">{{empform.empGender}}</span>
                                                </el-col>
                                            </el-row>
                                            <el-row type="flex" style="margin-top: 35px">
                                                <el-col :span="3">
                                                    <span style="color: gray">部门：</span>
                                                </el-col>
                                                <el-col :span="9">
                                                    <span style="color: black">{{empform.depId.depName}}</span>
                                                </el-col>
                                                <el-col :span="3">
                                                    <span style="color: gray">岗位：</span>
                                                </el-col>
                                                <el-col :span="4">
                                                    <span style="color: black">{{empform.roleId.roleName}}</span>
                                                </el-col>
                                            </el-row>
                                            <el-row type="flex" style="margin-top: 35px">
                                                <el-col :span="3">
                                                    <span style="color: gray">联系电话：</span>
                                                </el-col>
                                                <el-col :span="9">
                                                    <span style="color: black">{{empform.empPhone}}</span>
                                                </el-col>
                                                <el-col :span="3">
                                                    <span style="color: gray">入职日期：</span>
                                                </el-col>
                                                <el-col :span="4">
                                                    <span style="color: black">{{empform.empSettime | formatDate}}</span>
                                                </el-col>
                                            </el-row>
                                            <el-row type="flex" style="margin-top: 35px">
                                                <el-col :span="3">
                                                    <span style="color: gray">工龄：</span>
                                                </el-col>
                                                <el-col :span="9">
                                                    <span style="color: black">{{empseniority}}</span>
                                                </el-col>
                                                <el-col :span="3">
                                                    <span style="color: gray">所居地：</span>
                                                </el-col>
                                                <el-col :span="9">
                                                    <span style="color: black">{{empform.empAdd}} {{empform.empDeadd}}</span>
                                                </el-col>
                                            </el-row>
                                        </div>
                                    </div>
                                </el-form>
                            </el-col>
                            <el-col :span="4">
                                <el-button @click="mypwddialog=true">修改密码</el-button>
                                <el-button @click="editPer">编辑信息</el-button>
                            </el-col>
                        </el-row>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>

        <!--弹出层-裁剪 -->
        <el-dialog
                title="编辑头像"
                :visible.sync="dialogVisible"
                :before-close="handleClose"
        >
            <span>
                <el-row>
                    <input
                        type="file"
                        id="uploads"
                        accept="image/png, image/jpeg, image/gif, image/jpg"
                        @change="uploadImg($event,1)"
                        class="el-button"
                        style="margin-bottom:15px"
                    >
                </el-row>
                <el-row>
                    <el-col :span="16">
                        <!--裁剪 -->
                            <vueCropper
                                    style="width:100%;height:300px"
                                    ref="cropper"
                                    :img="attach.customaryUrl"
                                    :autoCrop="options.autoCrop"
                                    :fixedBox="options.fixedBox"
                                    :canMoveBox="options.canMoveBox"
                                    :autoCropWidth="options.autoCropWidth"
                                    :autoCropHeight="options.autoCropHeight"
                                    :centerBox="options.centerBox"
                                    @realTime="realTime"
                            >

                            </vueCropper>
                    </el-col>
                    <el-col :span="8">
                        <h2 align="center">头像预览</h2>
                            <div class="show-preview">
                                <div :style="previews.div" class="preview">
                                    <img :src="previews.url" :style="previews.img">
                                </div>
                            </div>
                    </el-col>
                </el-row>
                <el-row class="footerBtn" align="center">
                    <el-button type="primary" size="small" round="" @click="cut('blob')">确认</el-button>
                    <el-button type="primary" size="small" round="" @click="handleClose">取消</el-button>
                </el-row>
            </span>
        </el-dialog>

        <!--修改密码-->
        <el-dialog
                width="470px" center
                title="修改密码"
                :visible.sync="mypwddialog"
                :before-close="handlemypwddialogClose"
        >
            <div style="height:240px;" class="scrollbar">
                <el-form :model="pwdform" ref="pwdform" :rules="mypwdrules" label-width="100px">
                    <el-form-item label="原密码：" prop="oldpwd">
                        <el-input v-model="pwdform.oldpwd" show-password style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="新密码：" prop="newpwd">
                        <el-input v-model="pwdform.newpwd" show-password style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="确认密码：" prop="truenewpwd">
                        <el-input v-model="pwdform.truenewpwd" show-password style="width: 250px"></el-input>
                    </el-form-item>
                </el-form>
                <el-button @click="truemypwd('pwdform')"
                           v-loading.fullscreen.lock="fullscreenLoading"
                           style="margin-left: 130px;" size="small" type="primary" plain>保存</el-button>
                <el-button style="margin-left: 10px;" size="small" type="primary" plain>返回</el-button>


            </div>
        </el-dialog>


        <!--编辑个人信息 -->
        <el-dialog center
                   width="470px"
                title="编辑个人资料"
                :visible.sync="personage"
                :before-close="handlepersonageClose"
        >
            <div style="height:300px;" class="scrollbar">
                <el-form :model="mypersonagefrom" ref="mypersonagefrom" label-width="100px">
                    <el-form-item label="电话号码：" prop="empPhone">
                        <el-input v-model="mypersonagefrom.empPhone" style="width: 250px"></el-input>
                    </el-form-item>
                    <el-form-item label="所居地：">
                        <!--el-cascader级联（城市选择器）-->
                        <el-cascader v-model="address" :options="cityoptions" ref="cascaderAddr" clearable
                                     style="width: 250px;" filterable @change="handleChange" placeholder="选择地址">
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="详细地址：" prop="empDeadd">
                        <el-input v-model="mypersonagefrom.empDeadd" style="width: 250px"></el-input>
                    </el-form-item>
                </el-form>
                <el-button @click="truemypersonage('mypersonagefrom')"
                           v-loading.fullscreen.lock="fullscreenLoading"
                           style="margin-left: 130px;" size="small" type="primary" plain>保存</el-button>
                <el-button style="margin-left: 10px;" size="small" type="primary" plain>返回</el-button>


            </div>
        </el-dialog>
    </div>
</template>

<script>
    import {formatTimeToStr} from '../router//format.js'
    import cities from '../router/cities.js'
    export default {
        name: "Dmypersonal",
        inject: ['reload'], // 引入方法

        data() {
            var yzOldPwd = (rule, value, callback) => {
                this.$axios.post("http://localhost:8088/myemp/verifymypwd",this.pwdform).then(v=> {
                    this.print("我是返回值");
                    this.print(v.data);
                    if(v.data=='old'){
                        callback(new Error('旧密码错误'));
                    }else {
                        callback();
                    }
                })
            };
            var yztwoPwd = (rule, value, callback) => {
                if(this.pwdform.newpwd !=this.pwdform.truenewpwd){
                    callback(new Error('两次密码不一致'));
                }else {
                    callback();
                }
            };
           return{
               myimage:'',//头像路径
               mypersonagefrom:{
                   empId:0,
                   empPhone:'',
                   empAdd:'',
                   empAddnum:'',
               },//个人资料表单

               address:[],//地址
               personage:false,//编辑个人信息弹框
               cityoptions: cities,//城市数据
               fullscreenLoading: false,//修改密码后页面加载重置
               /*修改密码表单*/
               mypwdrules:{
                   olepwd: [
                       {required: true, message: '请输入原密码', trigger: ['blur','change']},
                       {validator: yzOldPwd}
                   ],
                   newpwd: [
                       {required: true, message: '请输入新密码', trigger: ['blur','change']},
                       {min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur'}
                   ],
                   truenewpwd: [
                       {required: true, message: '请再次输入新密码', trigger:  ['blur','change']},
                       {validator: yztwoPwd}

                   ]

               },

               mypwddialog:false,//修改密码弹框
               empseniority:'',

               /*密码表单*/
               pwdform:{
                   empId:0,
                   oldpwd:'',
                   newpwd:'',
                   truenewpwd:''
               },

               /*员工表单*/
               empform:{
                   empId:0,
                   empName:'',
                   empGender:'',
                   empPhone:'',
                   empAdd:'',
                   empAddnum:'',
                   empDeadd:'',
                   empSfz:'',
                   empSettime:'',
                   empImgpath:'',
                   depId:{
                       depId:0,
                       depName:'',
                   },
                   empDepnum:'',
                   roleId:{
                       roleId:0,
                       roleName:''
                   }
               },
               /*对齐方式*/
               labelPosition:'left',
               activeName:'first',
               dialogVisible:false,
               options:{
                   autoCrop:true,  //默认生成截图框
                   fixedBox:true,  //固定截图框大小
                   canMoveBox:false,    //截图框不能拖动
                   autoCropWidth:200,  //截图框宽度
                   autoCropHeight:200, //截图框高度
                   centerBox:false,    //截图框被限制在图片里面
               },
               previews:{}, //实时预览图数据
               attach:{ //后端附件表
                   id:'',
                   userId:'',
                   customaryUrl:'', //原图片路径
                   laterUrl:'',//裁剪后图片路径  /static/logo.png
                   attachType:'photo',//附件类型
               },
               fileName:'',//本机文件地址
               uploadImgRelaPath:'',//上传后图片地址
           }
        },

        methods: {
            //打开上传头像弹框
            clickUpload(){

                this.attach.customaryUrl = this.empform.empImgpath;
                this.dialogVisible=true;
            },
            /*修改个人资料*/
            editPer(){
                this.mypersonagefrom = JSON.parse(JSON.stringify(this.mypersonagefrom));
                this.personage=true;
            },
            /*确认修改资料*/
            truemypersonage(viod){
                this.$refs[viod].validate((valid) => {
                    if(valid){
                        var empfrom = JSON.stringify({empfrom:this.mypersonagefrom});
                        this.$axios.post("http://localhost:8088/myemp/addmyempfrom",this.qs.stringify(
                            {empfrom:empfrom}
                        )).then(v=> {
                            if(v.data =='editsucceed'){
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                });

                                this.personage=false;
                                this.reload();
                            }

                        })
                    }else {
                        return false;
                    }
                })
            },

            /*关闭编辑个人信息弹框*/
            handlepersonageClose(){
                this.personage= false;
                var strings = this.empform.empAddnum.split("/");
                this.print(strings);
                strings.forEach(s=>{
                    this.address.push(s)
                })

            },

            /*确认保存新密码*/
            truemypwd(pwdform){
                this.pwdform.empId = this.empform.empId;
                this.$refs[pwdform].validate(valid => {
                    if (valid) {
                        this.$axios.post("http://localhost:8088/myemp/verifymypwd",this.pwdform).then(v=> {
                            this.print("我是返回值");
                            this.print(v.data);
                            if(v.data=='old'){
                                this.$message({
                                    showClose: true,
                                    message: '旧密码错误！',
                                    type: 'warning'
                                });
                            }else if(v.data=='succeed'){
                                this.$message({
                                    type: 'success',
                                    message: '修改成功!'
                                });
                                this.mypwddialog = false;//关闭修改密码弹框
                                this.fullscreenLoading = true;
                                setTimeout(() => {
                                    this.fullscreenLoading = false;
                                    this.$router.push({
                                        path: "/login",
                                    });
                                }, 3500);
                            }
                        })
                    }else{

                        return false;
                    }

                });
            },

            /*关闭修改密码弹框方法*/
            handlemypwddialogClose(){

                this.mypwddialog = false;
                this.pwdform={
                    oldpwd:'',
                    newpwd:'',
                    truenewpwd:''
                };/*重置密码表单*/

            },

            /*初始化员工信息*/
            initempfrom(){
                var empId = JSON.parse(window.localStorage.getItem('user')).empId;
                this.$axios.post("http://localhost:8088/myemp/selectBymyempId",this.qs.stringify(
                    {empId:empId}
                )).then(v=> {
                    console.log("tupian:"+v.data.empImgpath);
                    this.empform = v.data;
                    this.empform.empImgpath = v.data.empImgpath;
                    this.pwdform.empId = empId;
                    this.mypersonagefrom=this.empform;
                    this.empseniority = this.dateSubMonth(this.empform.empSettime);/*计算工龄*/
                    var strings = this.empform.empAddnum.split("/");
                    strings.forEach(s=>{
                        this.address.push(s)
                    })


                })
            },

            //控制弹出层关闭
            handleClose(){
                this.dialogVisible=false
            },
            //实时预览
            realTime(data){
                this.previews=data
            },
            //加载头像信息
            find(){
                this.myimage = localStorage.getItem('imgpath');
            },
            //选择本地图片
            uploadImg(e){
                var file = e.target.files[0];
                if(!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)){
                    this.$message.error('图片类型必须是.gif,jpeg,jpg,png,bmp中的一种');
                    return false;
                }
                console.log(e.target.result);
                //fileReader 接口，用于异步读取文件数据
                var reader = new FileReader();
                reader.readAsDataURL(file); //重要 以dataURL形式读取文件
                reader.onload = e => {

                    // data = window.URL.createObjectURL(new Blob([e.target.result])) 转化为blob格式

                    let data = e.target.result

                    this.attach.customaryUrl=data
                    // 转化为base64
                    // reader.readAsDataURL(file)
                    // 转化为blob
                }
            },
            //确认截图,上传
            cut(){
                var formData = new FormData();
                this.$refs.cropper.getCropBlob(res=>{
                    //res是裁剪后图片的bolb对象
                    formData.append("file",res);
                    this.$axios.post("http://localhost:8088/personageimage",formData).then(v=> {
                        this.dialogVisible = false;
                        localStorage.setItem('imgpath',v.data);//存用户头像
                        // 刷新
                        this.reload();
                    })

                })
            },
            dateSubMonth(date) {
                var date1 = new Date(date);
                var date2 = new Date();
                var monthCount = parseInt(date2.getFullYear() - date1.getFullYear()) * 12 - date1.getMonth() + date2.getMonth();
                var resM = monthCount % 12;
                var resY = parseInt(monthCount / 12);
                var resStr = "";
                if (resY != 0) {
                    resStr += resY + "年"
                }
                if (resM != 0) {
                    resStr += resM + "月"
                }
                if (resStr == "") {
                    resStr = "0";
                }
                return resStr;
            },
            // 获取省市区地址级联
            handleChange(e, form, thsAreaCode) {
                thsAreaCode = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels// 注意2： 获取label值
                window.console.log(thsAreaCode);// 注意3： 最终结果是个一维数组对象
                window.console.log(thsAreaCode[0] + thsAreaCode[1] + thsAreaCode[2]);
                const checkedNodes = this.$refs['cascaderAddr'].getCheckedNodes();
                window.console.log(checkedNodes[0].pathLabels); // 获取由 label 组成的数组
                //省市区赋值
                this.empform.empAdd = thsAreaCode[0] +'/'+ thsAreaCode[1] +'/'+ thsAreaCode[2];

                this.empform.empAddnum = e[0] +'/'+ e[1] +'/'+ e[2];

                this.address=e;
                window.console.log(typeof e);
                window.console.log(e);
                window.console.log("结果1"+e);
                window.console.log("结果2"+form);
                window.console.log("结果3"+thsAreaCode);
            }
        },
        created() {
            this.initempfrom();
        },
        watch: {


        },
        filters: {
            formatDate: function (time) {
                if (time != null && time != "") {
                    var date = new Date(time);
                    return formatTimeToStr(date, "yyyy-MM-dd");
                } else {
                    return "";
                }
            },
        },


    }
</script>

<style scoped>
    /* 弹性布局 水平居中 */
    .show-preview{
        display: flex;
        justify-content: center;
    }

    .preview{
        border-radius: 50%;
        overflow: hidden;
        border:1px solid #cccccc;
        background: #cccccc;
    }
    .footerBtn{
        display: flex;
        justify-content: center;
        margin-top: 15px;
    }
</style>